import React, { useState, useEffect } from 'react'

const themes = {
    light: {
        color: '#fff',
        background: 'gray'
    },
    dark: {
        color: 'green',
        background: 'orange'
    }
}
// 创建Context组件
const ThemeContext = React.createContext({
    theme: 'dark',
    toggle: () => { } // 向上下文设定一个回调方法
})
class About extends React.Component {
    constructor(props) {
        super(props)

        this.toggle = () => {
            // 设定toggle方法，会作为context参数传递
            this.setState(state => ({
                theme: state.theme === themes.dark ? themes.light : themes.dark
            }))
        }

        this.state = {
            theme: themes.light,
            toggle: this.toggle
        }
    }

    render() {
        return (
            <ThemeContext.Provider value={this.state}>
                <Content />
            </ThemeContext.Provider>
        )
    }
}

// 中间组件
function Content() {
    return (
        <ThemeContext.Consumer>
            {({ theme, toggle }) => (
                <div>
                    {JSON.stringify(theme)}
                    <Button />
                </div>
            )}
        </ThemeContext.Consumer>
    )
}

// 接收组件
function Button() {
    return (
        <ThemeContext.Consumer>
            {({ theme, toggle }) => (
                <button
                    onClick={toggle} // 调用回调
                    style={theme}>
                    > Toggle Theme
                </button>
            )}
        </ThemeContext.Consumer>
    )
}

export default About
